package com.yunshipei.utils;

import android.text.TextUtils;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class EncUtils {

    public static byte[] getEncData(String path, String key) throws IOException {
        byte[] chars = key.getBytes();
        int keyLen = key.length();
        try {
            byte[] data = FileUtils.toByteArray(path);
            int dataLen = data.length;
            byte[] result = new byte[dataLen];
            for (int i = 0; i < dataLen; i++) {
                result[i] = (byte) (data[i] ^ chars[i % keyLen]);
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String encrypt(String uuid, byte[] data) {
        String key = Aes.generateKey(uuid);
        try {
            return Aes.encryptBASE64(Aes.encrypt(data, key));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String decrypt(String uuid, String data) {
        String key = Aes.generateKey(uuid);
        try {
            return new String(Aes.decrypt(Aes.decryptBASE64(data), key));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String dealSeparator(String host, String path) {
        int length = host.length();
        if (!TextUtils.isEmpty(host) && !TextUtils.isEmpty(path)) {
            if ((host.charAt(length - 1) == '/' && path.charAt(0) != '/')
                    || (host.charAt(length - 1) != '/' && path.charAt(0) == '/')) {
                return host + path;
            } else if (host.charAt(length - 1) == '/' && path.charAt(0) == '/') {
                return host + path.substring(1, path.length());
            } else if (host.charAt(length - 1) != '/' && path.charAt(0) != '/') {
                return host + File.separator + path;
            }
        }
        return null;
    }
}  